package GUI;

import model.*;
import controller.*;
import order.*;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class HistoryPanel extends JPanel{

	JScrollPane scroller;
	ArrayList<JLabel> orderLabelList;
	ArrayList<JButton> commitList;
	ArrayList<JButton> undoList;
	ArrayList<Order> orderList;
	JPanel content;
	Client client;
	
	public HistoryPanel(Client _client){
	  	
		client = _client;
	
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		setBorder (BorderFactory.createTitledBorder(
				BorderFactory.createEtchedBorder (), "Order History"));
	  	content = new JPanel();
	  	content.setLayout(new GridLayout(30, 1, 10, 10));
	  	
		scroller = new JScrollPane(content);
		scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	  	
	  	add(scroller);
	  	
	  	orderLabelList = new ArrayList<JLabel> ();
	  	commitList = new ArrayList<JButton> ();
	  	undoList = new ArrayList<JButton> ();
	  	orderList = new ArrayList<Order>();
	}
	
public void addHistory(Order order){
		  JPanel thePanel;
		  JLabel orderLabel;
		  JButton commit, undo;
		  
	      thePanel = new JPanel();
		  BoxLayout layout = new BoxLayout(this.getRootPane() ,BoxLayout.Y_AXIS);
		  getRootPane().setLayout(layout);
		  	  
		  orderLabel = new JLabel(order.printOrder());
		  commit = new JButton("Commit");
		  undo = new JButton("Undo");
		  orderLabelList.add(orderLabel);
		  
		  commitList.add(commit);
		  undoList.add(undo);
		  orderList.add(order);
		  
		  thePanel.add(orderLabel);
		  thePanel.add(commit);
		  thePanel.add(undo);

		  content.add(thePanel);

		  commit.addActionListener(new commitListener(commit)); 
		  undo.addActionListener(new undoListener(undo));
		  
		 // client.addOrder(order);
	}
	
    public void update(){
		content.removeAll();
		content.revalidate();
		content.repaint();
		orderLabelList.clear();
		commitList.clear();
		orderList.clear();
		
	}
	
	class commitListener implements ActionListener{
		private JButton button;
		public commitListener(JButton _button){
			button = _button;
		}
		public void actionPerformed(ActionEvent arg0) {
			  button.setEnabled(false);
			  int index = commitList.indexOf(button);
			 // client.commitOrder(index);
			
		}
		
	}
	
	class undoListener implements ActionListener{
		private JButton button;
		public undoListener(JButton _button){
			button = _button;
		}
		public void actionPerformed(ActionEvent arg0) {
			  button.setEnabled(false);
			  int index = undoList.indexOf(button);
			  commitList.get(index).setEnabled(false);
			  Order order = orderList.get(index);
			  order.undoOrder();
		}
		
	}
}
